﻿using System.Threading.Tasks;
using iSlideTools.LocalServer.Data;
using iSlideTools.LocalServer.Models;
using iSlideTools.LocalServer.Options;
using iSlideTools.LocalServer.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace iSlideTools.LocalServer.Controllers
{
    [Route("api/[controller]")]
    public class VerifyTextController : Controller
    {
        private readonly TokenServer _tokenServer;
        private readonly DataContext _dataContext;

        public VerifyTextController(IOptions<JwtIssuerOptions> jwtOptions,
            IOptions<SecretKeyOptions> secretKeyOptions, DataContext dataContext)
        {
            _tokenServer = new TokenServer(jwtOptions.Value, secretKeyOptions.Value);
            _dataContext = dataContext;
        }

        [HttpPost("GenerateToken")]
        [AllowAnonymous]
        public async Task<IActionResult> GenerateToken([FromBody] ValidApp app)
        {
            var identity = await _tokenServer.AppValidate(app);
            if (identity == null)
                return BadRequest("无效的身份信息");

            var json = await _tokenServer.GenerateToken(identity);
            return new OkObjectResult(json);
        }

        [HttpGet("GetAll")]
        [Authorize(Policy = AuthorizationInfo.LoginUserPolicy)]
        public async Task<IActionResult> GetAll()
        {
            var textManagements = await _dataContext.TextManagement.ToListAsync();
            var json = JsonConvert.SerializeObject(textManagements, _tokenServer.JsonSerializerSettings);
            return new OkObjectResult(json);
        }
    }
}